package com.zf.shuashua;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.webkit.WebView;

import androidx.multidex.MultiDex;

import com.aliyun.apsara.alivclittlevideo.sts.OnStsResultListener;
import com.aliyun.apsara.alivclittlevideo.sts.StsInfoManager;
import com.aliyun.common.httpfinal.QupaiHttpFinal;
import com.aliyun.downloader.DownloaderManager;
import com.aliyun.private_service.PrivateService;
import com.aliyun.svideo.base.sts.StsInfo;
import com.aliyun.svideo.base.sts.StsInfoService;
import com.aliyun.svideo.base.sts.StsTokenInfo;
import com.aliyun.sys.AlivcSdkCore;
import com.dydroid.ads.c.ADLoader;
import com.dydroid.ads.c.AdClientConfig;
import com.huawei.openalliance.ad.inter.HiAd;
import com.kk.taurus.playerbase.config.PlayerConfig;
import com.kk.taurus.playerbase.config.PlayerLibrary;
import com.mediamain.android.view.base.FoxSDK;
import com.duoyou.task.openapi.DyAdApi;
import com.meis.base.mei.utils.AppUtils;
import com.miui.zeus.mimo.sdk.MimoSdk;
import com.qq.e.ads.cfg.MultiProcessFlag;
import com.qq.e.comm.managers.GDTADManager;
import com.qq.e.comm.managers.setting.GlobalSetting;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.vise.log.ViseLog;
import com.vise.log.inner.LogcatTree;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.interceptor.HttpLogInterceptor;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.advert.OpenAdvertActivity;
import com.zf.shuashua.advert.TTAdManagerHolder;
import com.zf.shuashua.advert.mg.AdDataBean;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.advert.AdvertConfigList;
import com.zf.shuashua.bean.advert.DrawConfigBean;
import com.zf.shuashua.bean.advert.HorizontalConfigBean;
import com.zf.shuashua.bean.advert.OpenConfigBean;
import com.zf.shuashua.bean.advert.ThirdAdOpen;
import com.zf.shuashua.helper.UmengHelper;
import com.zf.shuashua.manager.ShunInitialManager;
import com.zf.shuashua.utils.Util;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.plugins.RxJavaPlugins;
import retrofit2.http.HEAD;

public class ShuaApplication extends Application {

    public static Application context;

    // 广告刷新频次
    public static int adRefreshRate = 4;
    // 横屏信息流广告频次
    public static int horizontalRate = 3;

    public static boolean isVivoOpen = false;
    public static boolean isHuaweiOpen = false;
    public static boolean isXiaomiOpen = false;
    public static String channel;
    public static String city;

    public static int multiple_min = 3;
    public static int multiple_max = 7;

    public static boolean is_bind_wechat;

    public static String token = "";
    public static String accessToken = "";

    private int appCount;
    private boolean isRunInBackground;
    private long leaveAppTime;
    public static boolean isHotOpen;
    public static int hotTime = 15000;

    public static boolean game_status;

    // 头部参数
    public static String androidId;
    public static String imei;
    public static String oaid = "";
    public static String sn = "";
    public static boolean hasFirstStart;
    public static String blackbox = "";

    public static Context getContext() {
        return context;
    }

    public static AdvertConfigList advertConfig;
    public static DrawConfigBean drawConfig;
    public static OpenConfigBean openConfig;

    public static HorizontalConfigBean horizontalConfig;
    public static ThirdAdOpen thirdAdOpen;

    public static Map<String, AdDataBean> adMap = new HashMap<>();
    public static Map<String, String> gdtClickIdMap = new HashMap<>();

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        syncChannelSource();
        token = Store.getInstance().getToken();
        accessToken = Store.getInstance().getAccessToken();

        initBackgroundCallBack();

        hasFirstStart = Store.getInstance().isFirstStart();

        setRxJavaErrorHandler();

        initWebview();
        //同意过隐私协议，可初始化第三方相关
        if (Store.getInstance().getPrivacy()) {
            ShunInitialManager.getInstance().initCommon(this);
        } else {
            //非主线程初始化友盟
            if (!getApplicationContext().getPackageName().equals(getCurrentProcessName())) {
                UmengHelper.getInstance().init();
            }
        }
    }

    private void initWebview(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = Util.getProcessName(context);
            if (!"com.zf.shuashua".equals(processName)) {//判断不等于默认进程名称
                WebView.setDataDirectorySuffix(processName);
            }
        }
    }

    private void syncChannelSource() {
        Store store = Store.getInstance();
        ShuaApplication.isVivoOpen = store.getVivoOpen();
        ShuaApplication.isHuaweiOpen = store.getHuaweiOpen();
        ShuaApplication.isXiaomiOpen = store.getXiaomiOpen();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static boolean isTuiaHomeOpen() {
        if (thirdAdOpen == null) {
            return Store.getInstance().isTuiaHomeOpen();
        }
        return thirdAdOpen.getAdvert_tuia_home_fuchuang_open() == 1;
    }

    public static boolean isTuiaTaskOpen() {
        if (thirdAdOpen == null) {
            return Store.getInstance().isTuiaTaskOpen();
        }
        return thirdAdOpen.getAdvert_tuia_quanping_open() == 1;
    }

    public static boolean isBxmOpen() {
        if (thirdAdOpen == null) {
            return Store.getInstance().isBxmOpen();
        }
        return thirdAdOpen.getAdvert_bianxianmao_open() == 1;
    }

    public static boolean isHwAdOpen() {
        if (thirdAdOpen == null) {
            return Store.getInstance().isHwAdOpen();
        }
        return thirdAdOpen.getAdvert_huaweiqudaoguanggao_open() == 1;
    }

    private void setRxJavaErrorHandler() {
        RxJavaPlugins.setErrorHandler(throwable -> {
        });
    }

    private void initBackgroundCallBack() {
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            }

            @Override
            public void onActivityStarted(Activity activity) {
                appCount++;
            }

            @Override
            public void onActivityResumed(Activity activity) {
                if (isRunInBackground) {
                    //应用从后台回到前台 需要做的操作
                    back2App(activity);
                }
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                appCount--;
                if (appCount == 0) {
                    //应用进入后台 需要做的操作
                    leaveApp(activity);
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
            }
        });
    }

    /**
     * 从后台回到前台需要执行的逻辑
     *
     * @param activity
     */
    private void back2App(Activity activity) {
        isRunInBackground = false;
        if (!isHotOpen) {
            return;
        }
        try {
            if (activity != null) {
                if (CommitUtils.isCloseGame()) {
                    return;
                }
                if (System.currentTimeMillis() - leaveAppTime <= hotTime) {
                    return;
                }
                activity.getWindow().getDecorView().postDelayed(() -> activity.startActivity(new Intent(activity, OpenAdvertActivity.class)), 400);
            }
        } catch (Exception ignored) {

        }
    }

    /**
     * 离开应用 压入后台或者退出应用
     *
     * @param activity
     */
    private void leaveApp(Activity activity) {
        leaveAppTime = System.currentTimeMillis();
        isRunInBackground = true;
    }

    /**
     * 获取当前进程名
     */
    private String getCurrentProcessName() {
        int pid = android.os.Process.myPid();
        String processName = "";
        ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService
                (Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) {
            if (process.pid == pid) {
                processName = process.processName;
            }
        }
        return processName;
    }
}